package luojiaoj

class StaticResourceController {
    def groovyPagesTemplateEngine
    def css = {
        def file = params.id
        def cssPath = servletContext.getRealPath("css/${file}.css")
        def resourceFile = new File(cssPath)
        if (!resourceFile.exists()) {
            // 404: Not Found
            render(text:"File Not Found",status:404)
            return
        }
        def buffer = null
        try {
            buffer = processTemplate(resourceFile, params)
        } catch (Exception ex) {
            log.error "Failed to process template", ex
        }

        if (buffer != null) {
            render(text:buffer, contentType:"text/css")
        } else {
            // 500: Internal Server Error
            render(text:"Failed to process template", status:500)
        }
    }
    def processTemplate(resourceFile, model) {
        def buffer = resourceFile.getText()
        def template = groovyPagesTemplateEngine.createTemplate(buffer,
                "${resourceFile.getPath()}")
        def writer = new StringWriter()
        template.make(model).writeTo(writer)
        return writer.toString()
    }
}
